import { Ctx, Next } from '../../types';
import { User as UserModel } from '../../database/entity/User.entity';

export default class user {

  public static async login (ctx: Ctx) {
    const { user, password } = ctx.request.body;
    
    const find = await UserModel.findOne({user});
    if(find) {
      const validataPass = await ctx.bcrypt.validate(password, find.password);
      if(!validataPass) {
        ctx.throw(400, ctx.error('密码错误'));
      }
      find.loginCount += 1;
      find.lastLoginTime = new Date();
      await UserModel.save(find);
    }else{
      ctx.throw(400, ctx.error('用户不存在'));
    }
    ctx.body = ctx.success({
      token: ctx.jwt.encode({
        userId: find.id,
        userName: find.user
      })
    });
  }

  public static async createUser(ctx: Ctx) {
    const { user, password } = ctx.request.body;
    const passHash = await ctx.bcrypt.parse(password);
    const find = await UserModel.findOne({
      user: user
    })
    if(find) {
      ctx.throw(400, ctx.error('已注册'));
    }

    const userData = new UserModel();
    userData.user = user;
    userData.password = passHash;
    userData.ip = ctx.ip;
    await UserModel.save(userData);
    ctx.body = ctx.success();
  }

  public static async updateUserPassword(ctx: Ctx, next: Next) {
    const { userId } = ctx.auth;
    const { oldPassword, newPassword, confirmPassword } = ctx.request.body;

    const find = await UserModel.findOne({ id: userId });
    
    const validataPass = await ctx.bcrypt.validate(oldPassword, find.password);
    
    if(!validataPass) {
      ctx.throw(400, ctx.error('旧密码密码错误'));
    }

    if(newPassword !== confirmPassword) {
      ctx.throw(400, ctx.error('两次密码不一致'));
    }

    find.password = await ctx.bcrypt.parse(newPassword);
    await UserModel.save(find);

    ctx.body = ctx.success();
    next();
  }

  public static async authUser(ctx: Ctx, next: Next) {
    ctx.auth.userId;
    ctx.body = ctx.success();
    next();
  }
}
